#!/usr/bin/env python

import os, sys
from checkers import impl, players, loggers
from checkers.main import play_game
from optparse import OptionParser

def main(options, args):

    fp = getattr(options, 'filename') or 'checkers.txt'
    fp = os.path.abspath(os.path.expanduser(fp))

    lock = fp + '.lock'
    # If no lock, wipe log and lock
    if not os.path.exists(lock):
        open(lock, 'w').close()
        open(fp, 'w').close()

    logs = [
        loggers.FileLogger(fp),
        loggers.DisplayLogger()
        ]

    depth = int(getattr(options, 'depth') or 2)

    s1 = getattr(options, 'player1') or 'alpha-beta'
    s2 = getattr(options, 'player2') or 'alpha-beta'

    l1 = logs[:]
    kw = {'loggers':l1}
    if s1 == 'file':
        del l1[0]
        kw['fp'] = fp
        kw['ask'] = False
        kw['out'] = sys.stdout
    if s1 == 'alpha-beta':
        kw['depth'] = depth
    p1 = players.Player(players.get_player(s1), **kw)

    l2 = logs[:]
    kw = {'loggers':l2}
    if s2 == 'file':
        del l2[0]
        kw['fp'] = fp
        kw['ask'] = False
        kw['out'] = sys.stdout
    if s2 == 'alpha-beta':
        kw['depth'] = depth
    p2 = players.Player(players.get_player(s2), **kw)

    result = play_game(impl.Checkers(impl.WHITE),
                       *(p1, p2))

    # If there's a lock, clear it.
    if os.path.exists(lock):
        os.remove(lock)

    print (result == 0 and 'TIE' or
           result > 0 and impl.WHITE or
           result < 0 and impl.BLACK)

def parse_cmd():
    parser = OptionParser()
    parser.add_option('-1', '--player1',
                      dest='player1',
                      help='Player 1 Strategy (defaults to alpha-beta)',
                      metavar='<STRATEGY>')
    parser.add_option('-2', '--player2',
                      dest='player2',
                      help='Player 2 Strategy (defaults to alpha-beta)',
                      metavar='<STRATEGY>')
    parser.add_option('-d', '--depth',
                      dest='depth',
                      help='Depth for alpha-beta prunning',
                      metavar='<DEPTH>')
    parser.add_option('-f', '--file',
                      dest='filename',
                      help=('Read (in case of file player) '
                            'and write using FILE'),
                      metavar='FILE')
    (options, args) = parser.parse_args()
    main(options, args)

if __name__ == '__main__':
    parse_cmd()
